<template>
  <div id="dialogCreateLab">
    <el-dialog
      title="添加用户标签"
      :visible.sync="dialogData.isShow"
      width="780px"
      @close="cancelLabel"
    >
      <div>
        <!-- 顶部搜索部分 -->
        <div class="search-box">
          <el-form
            ref="ruleForm"
            :inline="true"
            :model="formInline"
            :rules="rules"
            class="demo-form-inline"
          >
            <el-form-item label="标签分类" prop="tagCategoryId">
              <el-select
                v-model="formInline.tagCategoryId"
                filterable
                placeholder="请选择"
                @change="getCurCategory"
                clearable
              >
                <el-option
                  v-for="item in tagCategoryIdList"
                  :key="item.id"
                  :label="item.tagCategoryName"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="标签" prop="tagIds">
              <el-select
                v-model="formInline.tagIds"
                @change="getCurTags"
                clearable
              >
                <el-option
                  v-for="item in tagsList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-button class="button" type="success" @click="handAdd">
              添加
            </el-button>
          </el-form>
        </div>
        <!-- 表格部分 -->
        <div id="table">
          <el-table :data="tableData" style="width: 100%" height="200">
            <el-table-column
              label="标签分类"
              prop="tagCategoryName"
              min-width="150"
            ></el-table-column>
            <el-table-column
              label="标签名"
              prop="name"
              min-width="150"
            ></el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="text" @click="delLine(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="form-box">
            <el-form
              ref="ruleForm"
              :model="ruleForm"
              :rules="rules"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item class="input" label="导入方式" prop="type">
                <el-select v-model="ruleForm.type" placeholder="请选择">
                  <el-option
                    v-for="item in typeList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
              <!--此处不用v-if,因为切换后，会不显示大鹏号，而显示userId-->
              <div :class="ruleForm.type === '1' ? 'hideClass' : ''">
                <el-form-item label="大鹏号" prop="dpNum">
                  <el-select
                    v-model="ruleForm.dpNum"
                    multiple
                    filterable
                    remote
                    :no-data-text="noData"
                    placeholder="请输入大鹏号"
                    :remote-method="remoteMethod"
                    :loading="inputLoading"
                    clearable
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.userId"
                      :label="item.dpNumber"
                      :value="item.userId"
                      :disabled="ruleForm.dpNum.length >= 5"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div :class="ruleForm.type === '0' ? 'hideClass' : ''">
                <importFile
                  :file-data="fileData"
                  :dialog-data="importDialogData"
                ></importFile>
              </div>
            </el-form>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="cancelLabel">取 消</el-button>
        <el-button
          type="success"
          :loading="loading"
          @click="confirmLabel('ruleForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { tagCategoryNames, getTagList } from '@/api/lableManage/tagCategory' // 接口
import { importUserLabel } from '@/api/lableManage/labelUser' // 接口
import { downloadUrl } from '@/api/system/user' // 接口
import { getDpNum } from '@/api/system/user' // 接口
import importFile from '@component/lableManage/common/importFile' // 导入
// 导入公用方法
export default {
  name: 'DialogCreateLab',
  msg: '用户管理-用户标签管理-创建标签用户 -弹框',
  components: {
    importFile
  },
  props: ['dialogData'],
  data() {
    return {
      showTitle: '创建标签用户',
      loading: false,
      inputLoading: false,
      total: 0,
      tableData: [], // table内容
      searchParams: {
        pageNum: 1, // 当前页数
        pageSize: 10, // 页面显示条数
        orderByColumn: 'robotNickname', // 排序字段
        isAsc: 'asc' // 正序倒序
      },
      formInline: {
        tagCategoryId: '',
        tagIds: ''
      },
      ruleForm: {
        type: '0', // 导入方式
        dpNum: [] // 大鹏号
      },
      options: [], // 大鹏号下拉列表
      noData: '请再输入至少10个字符',
      fileData: {
        labelName: '批量导入', // label名称
        fileName: '', // 上传文件名称
        upFile: '' // 上传文件
      },
      // 传递给导入弹框的数据
      importDialogData: {
        downUrl: '' // 下载模板接口
      },
      tagCategoryIdList: [], //标签分类列表
      tagsList: [], //标签列表
      curCategory: {}, //当前选中标签分类
      curTags: {}, //当前选中标签
      typeList: [
        // 导入方式列表
        { label: '手动输入', value: '0' },
        { label: '批量导入', value: '1' }
      ],
      rules: {
        dpNum: { required: true, message: '大鹏号不能为空', trigger: 'change' }
      }
    }
  },
  watch: {
    'ruleForm.type': {
      handler(newV, oldV) {
        if (newV === '0') {
          //手动输入
          this.rules.dpNum.required = true
        } else {
          //批量导入
          this.rules.dpNum.required = false
        }
      },
      deep: true
    }
  },
  mounted() {
    this.getTagCategoryIdList()
    this.importDialogData.downUrl = downloadUrl()
  },
  methods: {
    /*获取标签分类列表*/
    getTagCategoryIdList() {
      tagCategoryNames(
        (response) => {
          this.tagCategoryIdList = response
        },
        (response) => {
          this.$message.warning(response.message)
        }
      )
    },
    /*获取标签列表*/
    getTagsList(id) {
      getTagList(id, (response) => {
        this.tagsList = response
      })
    },
    /*标签分类选中值改变*/
    getCurCategory(id) {
      this.formInline.tagIds = ''
      this.curTags = {}
      this.tagsList = []
      if (id) {
        this.curCategory = this.tagCategoryIdList.find((item) => {
          return item.id === id
        })
        this.getTagsList(id)
      } else {
        this.curCategory = {}
      }
    },
    /*获取当前选中标签*/
    getCurTags(id) {
      this.curTags = this.tagsList.find((item) => {
        return item.id === id
      })
    },
    /*选中标签添加到 table 中*/
    handAdd() {
      if (!this.curTags || !this.curTags.id) return
      let i = this.tableData.findIndex((item) => item.id === this.curTags.id)
      //数据重复，不允许加入this.tableData
      if (this.tableData.length > 0 && i >= 0) return
      let { tagCategoryName } = this.curCategory
      let obj = Object.assign({}, { tagCategoryName }, this.curTags)
      this.tableData.push(obj)
    },
    /*删除*/
    delLine(i) {
      this.tableData.splice(i, 1)
    },
    /*获取大鹏号*/
    getDapengNum(dpAccounts) {
      return new Promise((resolve, reject) => {
        let obj = { type: 'DPACCOUNT', value: dpAccounts }
        getDpNum(
          obj,
          (response) => {
            resolve(response)
          },
          (response) => {
            this.$message.warning(response.message)
            resolve([])
          }
        )
      })
    },
    /*输入框内容改变时，执行*/
    async remoteMethod(query) {
      /* console.log("query",query)*/
      query = query.trim()
      let _this = this
      if (query.length > 9) {
        _this.inputLoading = true
        let result = await this.getDapengNum(query)
        let ary = result.rows
        if (ary.length === 0) {
          setTimeout(() => {
            _this.options = []
            _this.inputLoading = false
            this.noData = '没有找到匹配大鹏号'
          }, 200)
        } else {
          setTimeout(() => {
            _this.options = [...ary]
            _this.inputLoading = false
            /* console.log("this.options=",this.options)*/
          }, 200)
        }
      } else {
        _this.options = []
        let n = 10 - query.length
        this.noData = `请再输入${n}个字符`
      }
    },
    /* 确认提交 */
    confirmLabel(formName) {
      if (this.tableData.length === 0) {
        this.$message({
          message: '请添加标签！',
          type: 'warning'
        })
        return
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.type === '0') {
            //手动输入
            this.subHand()
          } else {
            // 批量导入
            if (!this.fileData.fileName) {
              this.$message({
                message: '请添加文件！',
                type: 'warning'
              })
              return
            }
            this.subImport()
          }
        } else {
          return false
        }
      })
    },
    /* 提交表单-批量导入 */
    subImport() {
      this.loading = true
      let tagIds = []
      this.tableData.forEach((item) => {
        tagIds.push(item.id)
      })
      let formData = new FormData()
      formData.append('file', this.fileData.upFile)
      formData.append('ids', tagIds)
      importUserLabel(
        formData,
        (response) => {
          this.loading = false
          this.$emit('refresh')
          this.cancelLabel()
        },
        (response) => {
          // 有上传失败的情况，弹出失败提示窗
          this.loading = false
          this.$emit('showError', response.message, 'tagManageDp', response)
          this.cancelLabel()
        }
      )
    },
    /* 提交表单-手动导入 */
    subHand() {
      //手动导入
      this.loading = true
      let tagIds = []
      this.tableData.forEach((item) => {
        tagIds.push(item.id)
      })
      let obj = {
        tagIds: tagIds,
        userIds: this.ruleForm.dpNum
      }
      importUserLabel(
        obj,
        (response) => {
          this.loading = false
          this.$emit('refresh')
          this.cancelLabel()
        },
        (response) => {
          // 上传失败
          this.loading = false
          this.$message.warning('新增失败,' + response.message)
        },
        `?binding`
      )
    },
    // 关闭对话框 清除表单数据
    cancelLabel() {
      // 关闭前清空
      this.loading = false
      this.dialogData.isShow = false
    }
  }
}
</script>
<style lang="less">
#dialogCreateLab {
  .hideClass {
    display: none;
  }
  .search-box {
    padding-left: 0 !important;
    .el-input {
      width: 220px !important;
    }
  }
  .el-autocomplete {
    width: 100%;
  }
  .el-dialog__body {
    padding-bottom: 10px !important;
  }
  .input {
    width: 400px !important;
  }
  .button {
    margin-top: 9px;
  }
}
</style>
